<?php

include_once($mcrp . 'functions/categories.php');

class ContestInfos
{
	var $id;
	var $title = 'Nouveau concours';
	var $description = '';
	var $description_en = '';
	var $variables = '';
	var $points = 20;
	var $validationcount = 0;
	var $category = -1;
	var $visible = false;
}

function CreateContest(&$ContestInfos)
{
	global $mcrp;
	global $mcsql;
	$ContestInfos->variables = '$sentvars = array(array());\n$recvvars = array(array());';
	$result = $mcsql->Query('INSERT INTO contests(title, description, variables, points, validationcount, category, visible) VALUES(\'' . $ContestInfos->title . '\', \'' . $ContestInfos->description . '\', \'' . $ContestInfos->variables . '\', ' . $ContestInfos->points . ', ' . $ContestInfos->validationcount . ', ' . $ContestInfos->category . ', ' . ($ContestInfos->visible?'TRUE':'FALSE') . ')');
	if($result === false) return false;
	$ContestInfos = GetContest($ContestInfos->title, $ContestInfos->category);
	CategoryAddContest($ContestInfos->category, $ContestInfos->id);
	
	$dir = $mcrp . 'contests/' . $ContestInfos->id . '/';
	$DefaultValidation = 
'<?php

$mcrp = \'./../../\';
define(\'MC_CONTEST\', ' . $ContestInfos->id . ');
include_once($mcrp . \'functions/session.php\');
include_once($mcrp . \'functions/variables.php\');
include_once($mcrp . \'contests/validation.php\');
$Success = false;

echo ValidateContest($Success, MC_CONTEST);

?>';
		
		$DefaultContest = 
'<?php

$mcrp = \'./../../\';
define(\'MC_CONTEST\', ' . $ContestInfos->id . ');
include_once($mcrp . \'functions/session.php\');
include_once($mcrp . \'functions/variables.php\');

DisplayVariables();

?>';

	if(mkdir($dir))
	{
		$f = fopen($dir . 'validation.php', 'w');
		if($f)
			fwrite($f, $DefaultValidation);
		fclose($f);
		$f = fopen($dir . 'contest.php', 'w');
		if($f)
			fwrite($f, $DefaultContest);
		fclose($f);
	}
	else
	{
		echo 'Erreur lors de la création du dossier';
	}
	return true;
}

function ClearDir($dossier)
{
	$ouverture=@opendir($dossier);
	if (!$ouverture) return;
	while($fichier=readdir($ouverture))
	{
		if ($fichier == '.' || $fichier == '..') continue;
		if (is_dir($dossier."/".$fichier))
		{
			$r=clearDir($dossier."/".$fichier);
			if (!$r) return false;
		}
		else
		{
			$r=@unlink($dossier."/".$fichier);
			if (!$r) return false;
		}
	}
	closedir($ouverture);
	$r=@rmdir($dossier);
	if (!$r) return false;
	return true;
}

function DeleteContest($Id)
{
	global $mcrp;
	global $mcsql;
	$mcsql->query('DELETE FROM contests WHERE id=' . $Id);
	ClearDir($mcrp . 'contests/' . $Id);
}

function GetContest($Title, $CatId)
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT * FROM contests WHERE title=\'' . $Title . '\' AND category=\'' . $CatId . '\'');
	if($contest = mysql_fetch_array($answer))
	{
		$ci = FillContestInfos($contest);
		return $ci;
	}
	return false;
}

function GetContestById($Id)
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT * FROM contests WHERE id=\'' . $Id . '\'');
	if($contest = mysql_fetch_array($answer))
	{
		$ci = FillContestInfos($contest);
		return $ci;
	}
	return false;
}

function GetAllContests($visible = true)
{
	global $mcsql;
	$contests = array();
	$answer = $mcsql->Query('SELECT * FROM contests WHERE visible=' . ($visible?1:0) . ' ORDER BY points ASC');
	while($contest = mysql_fetch_array($answer))
	{
		$ci = FillContestInfos($contest);
		$contests[$contest['id']] = $ci;
	}
	return $contests;
}

function GetContestsCount()
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT COUNT(*) FROM contests WHERE visible=1');
	$res = mysql_fetch_array($answer);
	return $res[0];
}

function GetContestsListByCategory($l)
{
	$contests = array();
	foreach($l as $id)
	{
		$c = GetContestById($id);
		$contests[$c->category][] = $c;
	}
	return $contests;
}

function FillContestInfos($Contest)
{
	$ci = new ContestInfos;
	$ci->title = addslashes($Contest['title']);
	$ci->description = addslashes($Contest['description']);
	$ci->description_en = addslashes($Contest['description_en']);
	$ci->id = (int)$Contest['id'];
	$ci->variables = addslashes($Contest['variables']);
	$ci->points = (int)$Contest['points'];
	$ci->validationcount = (int)$Contest['validationcount'];
	$ci->category = (int)$Contest['category'];
	$ci->visible = (bool)$Contest['visible'];
	return $ci;
}

function GetContestsByCategoryId($Id, $Visible=true)
{
	global $mcsql;
	$contests = array();
	$answer = $mcsql->Query('SELECT * FROM contests WHERE category=\'' . $Id . '\' AND visible=' . (int)$Visible . ' ORDER BY points ASC');
	while($c = mysql_fetch_array($answer))
	{
		$ci = FillContestInfos($c);
		$contests[] = $ci;
	}
	return $contests;
}

function UpdateContest($ContestInfos)
{
	global $mcsql;
	return $mcsql->Query('UPDATE contests SET title=\'' . $ContestInfos->title . '\', description=\'' . $ContestInfos->description . '\', description_en=\'' . $ContestInfos->description_en . '\', variables=\'' . $ContestInfos->variables . '\', points=' . $ContestInfos->points . ', validationcount=' . $ContestInfos->validationcount . ', visible=' . ($ContestInfos->visible?1:0) . ' WHERE id=' . $ContestInfos->id);
}

function UpdateContestCategory($ContestInfos, $OldCategory)
{
	global $mcsql;
	$result = $mcsql->Query('UPDATE contests SET category=' . $ContestInfos->category . ' WHERE id=' . $ContestInfos->id);
	/*CategoryRemoveContest($OldCategory, $ContestInfos->id);
	CategoryAddContest($ContestInfos->category, $ContestInfos->id);*/
}

function ComputeContestsPoints($force = false)
{
	$contests = GetAllContests();
	if($force) ResetUsersPoints();
	foreach($contests as $c)
	{
		$OldPoints = $c->points;
		$up = ComputeContestPoints($c);
		if($force || $up)
		{
			UpdateContest($c);
			if($force)
				UpdateUsersPoints($c->id, -$c->points);
			else
				UpdateUsersPoints($c->id, $OldPoints - $c->points);
		}
	}
}

function ComputeContestPoints(&$ci)
{
	$M = GetActiveUsersCount();
	$A = 20.; // points maximum
	$B = 19.;
	$C = 8.;
	$D = 1.;
	$alpha = 0.1*$M;	// pourcentage en dessous duquel on utilise la loi 1 (ie A)
	$beta = 0.5*$M;
	$gamma = 0.9*$M;
	$x = (float)$ci->validationcount;
	
	if($x <= $alpha)
	{
		$points = round($x*($B-$A)/$alpha+$A);
	}
	else if($x > $alpha && $x <= $beta)
	{
		$points = round($x*($C-$B)/($beta-$alpha)+($beta*$B-$alpha*$C)/($beta-$alpha));
	}
	else if($x > $beta && $x <= $gamma)
	{
		$points = round($x*($D-$C)/($gamma-$beta)+($gamma*$C-$beta*$D)/($gamma-$beta));
	}
	else if($x > $gamma)
	{
		$points = $D;
	}
	
	if($ci->points == $points)
		return false;
	$ci->points = $points;
	return true;
}

function GetLastContests($count = 5)
{
	global $mcrp;
	$lastc = file_get_contents($mcrp . 'config/lastcontests');
	$lastc = explode(' ', $lastc);
	$max = count($lastc);
	$contests = array();
	for($i = 0; $i<(min($count, $max)); $i++)
	{
		$contests[$i]['con'] = GetContestById($lastc[$i]);
		$contests[$i]['cat'] = GetCategoryById($contests[$i]['con']->category);
	}
	return $contests;
}

function AddLastContest($id)
{
	global $mcrp;
	$lastc = file_get_contents($mcrp . 'config/lastcontests');
	$lastc = $id . ' ' . $lastc;
	file_put_contents($mcrp . 'config/lastcontests', $lastc);
}

function GetLastValidations($count)
{
	global $mcrp;
	$lastv = file_get_contents($mcrp . 'config/lastvalidations');
	$lastv = explode(' ', $lastv);
	$lastvv = array();
	foreach($lastv as $v)
		$lastvv[] = explode(',', $v);
	$validations = array();
	$max = count($lastvv);
	for($i = 0; $i<(min($count, $max)); $i++)
	{
		$v = $lastvv[$i];
		$validations[] = array('u' => GetUserById($v[0]), 'c' => GetContestById($v[1]), 't' => $v[2]);
	}
	return $validations;
}

function AddLastValidation($u, $c)
{
	global $mcrp;
	$lastv = file_get_contents($mcrp . 'config/lastvalidations');
	$lastv = $u . ',' . $c . ',' . time() . ' ' . $lastv;
	file_put_contents($mcrp . 'config/lastvalidations', $lastv);
}


function GetMaxPoints()
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT SUM(points) FROM contests WHERE visible=1');
	$res = mysql_fetch_array($answer);
	return $res[0];
}

?>